//
// Created by EDZ on 2022/2/18.
//

#ifndef INC_2022_1_TWOPOINTER_H
#define INC_2022_1_TWOPOINTER_H
#include "../head/common.h"

vector<vector<int>> threeSum(vector<int>& nums) {
    sort(nums.begin(),nums.end());
    vector<vector<int>> res;
    int n = nums.size();

    for(int i=0;i<n;i++){
        int n1 = nums[i];
        int p1 = i+1,p2 = n-1;
        while(p1<p2){
            while(n1+nums[p1]+nums[p2]>0&&p1<p2){
                p2--;
            }
            while(n1+nums[p1]+nums[p2]<0&&p1<p2){
                p1++;
            }
            if(n1+nums[p1]+nums[p2]==0&&p1<p2){
                res.push_back({n1,nums[p1],nums[p2]});
                p1++;
                p2--;
            }
        }
    }
    set<vector<int>> s(res.begin(), res.end());
    res.assign(s.begin(), s.end());
    return res;

}
int threeSumClosest(vector<int>& nums, int target) {
    sort(nums.begin(),nums.end());
    int n = nums.size();
    int difAbs = INT16_MAX,dif;
    for(int i=0;i<n;i++){
        int n1 = nums[i];
        int p1 = i+1,p2 = n-1;

        while(p1<p2){
            if(n1+nums[p1]+nums[p2]==target)
                return target;
            if(difAbs>abs(n1+nums[p1]+nums[p2]-target)){
                dif = n1 + nums[p1]+nums[p2]-target;
                difAbs = abs(n1+nums[p1]+nums[p2]-target);
            }
            if(n1+nums[p1]+nums[p2]>target){
                p2--;
            }
            else{
                p1++;
            }
        }
    }
    return dif+target;
}

#endif //INC_2022_1_TWOPOINTER_H
